package com.qdxht.dispenser.base;

import android.content.Context;
import android.graphics.Bitmap;
import android.serialport.SerialPort;
import androidx.multidex.MultiDexApplication;
import com.hjq.http.ssl.HttpSslConfig;
import com.hjq.http.ssl.HttpSslFactory;
import com.qdxht.dispenser.base.manager.ActivityManager;
import com.qdxht.dispenser.ui.models.entity.ConfigEntity;
import com.qdxht.dispenser.utils.ConfigUtil;
import com.qdxht.dispenser.utils.SpUtils;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.qdxht.dispenser.http.glide.GlideApp;
import com.qdxht.dispenser.http.model.RequestHandler;
import com.qdxht.dispenser.http.model.RequestServer;
import com.qdxht.dispenser.ui.view.MyLoadViewFactory;
import com.qdxht.dispenser.utils.DebugLoggerTree;
import com.qdxht.dispenser.utils.TitleBarStyle;
import com.qdxht.dispenser.utils.ToastStyle;
import com.hjq.bar.TitleBar;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.http.EasyConfig;
import com.hjq.toast.ToastUtils;
import com.shizhefei.mvc.MVCHelper;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import timber.log.Timber;
import com.baidu.location.LocationClient;

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2018/10/18
 *    desc   : 应用入口
 */
public final class AppApplication extends MultiDexApplication {

    boolean loadLazySdk = false;

    @Override
    public void onCreate() {
        super.onCreate();
        initSdk();
        ConfigEntity config = ConfigUtil.getConfig();
        if(config == null){
            config = new ConfigEntity();
            ConfigUtil.saveConfig(config);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        // 清理所有图片内存缓存
        GlideApp.get(this).onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        // 根据手机内存剩余情况清理图片内存缓存
        GlideApp.get(this).onTrimMemory(level);
    }

    /**
     * 初始化本地框架
     */
    private void initSdk() {
        try {
            // 百度定位SDK初始化
            LocationClient.setAgreePrivacy(true);
        } catch (Exception e) {
            System.err.println("百度定位SDK初始化异常："+e.getMessage());
        }

        // 设置标题栏初始化器
        TitleBar.setDefaultStyle(new TitleBarStyle());
        // 设置LoadView的factory，用于创建使用者自定义的加载失败，加载中，加载更多等布局,写法参照DeFaultLoadViewFactory
        MVCHelper.setLoadViewFractory(new MyLoadViewFactory());
        // 初始化吐司
        ToastUtils.init(this, new ToastStyle());
        // 设置调试模式
        ToastUtils.setDebugMode(AppConfig.isDebug());
        // Activity 栈管理初始化
        ActivityManager.getInstance().init(this);

        // MMKV 初始化
        MMKV.initialize(this);
        SpUtils.getInstance();
        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)
                .setDownsampleEnabled(true)        //开启向下采样以保证大图加载
                .setResizeAndRotateEnabledForNetwork(true) // 对网络图片进行resize处理，减少内存消耗
                .setBitmapsConfig(Bitmap.Config.RGB_565)//因为Fresco默认图片格式是RGB_8888，这就对内存占用很高，所以可以用内存开销低一些的配置方式，比如：RGB_4444、RGB_565;
                .build();
        Fresco.initialize(this, config);

        HttpSslConfig sslConfig = HttpSslFactory.generateSslConfig();
        // 网络请求框架初始化
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .sslSocketFactory(sslConfig.getSslSocketFactory(), sslConfig.getTrustManager())
            .hostnameVerifier(HttpSslFactory.generateUnSafeHostnameVerifier());
        builder.readTimeout(AppConfig.API_TIMEOUT, TimeUnit.MILLISECONDS);
        builder.writeTimeout(AppConfig.API_TIMEOUT, TimeUnit.MILLISECONDS);
        builder.connectTimeout(AppConfig.API_TIMEOUT, TimeUnit.MILLISECONDS);
        EasyConfig.with(builder.build())
                // 是否打印日志
                .setLogEnabled(AppConfig.isDebug())
                // 设置服务器配置
                .setServer(new RequestServer())
                // 设置请求处理策略
                .setHandler(new RequestHandler(this))
                // 设置请求重试次数
                .setRetryCount(0)
                .into();

        // 设置 Json 解析容错监听
        GsonFactory.setJsonCallback((typeToken, fieldName, jsonToken) -> {
            // 上报到 Bugly 错误列表
            CrashReport.postCatchedException(new IllegalArgumentException(
                    "类型解析异常：" + typeToken + "#" + fieldName + "，后台返回的类型为：" + jsonToken));
        });

        // 初始化日志打印
        if (AppConfig.isLogEnable()) {
            Timber.plant(new DebugLoggerTree(this));
        }
        //需要在打开串口前调用
        SerialPort.setSuPath("/system/xbin/su");
        initLazySdk();
    }

    /**
     * 初始化第三方框架
     */
    public void initLazySdk() {
        // Bugly 异常捕捉
        CrashReport.initCrashReport(this, AppConfig.getBuglyId(), AppConfig.isDebug());
    }

    public boolean isLoadLazySdk() {
        return loadLazySdk;
    }

    public void setLoadLazySdk(boolean loadLazySdk) {
        this.loadLazySdk = loadLazySdk;
    }
}